/* eslint-disable */
import { msg } from '@/global'
import { RouteRecordRaw } from 'vue-router'

let firstRoute: RouteRecordRaw | undefined

// 根据 @/router/main 下的文件结构构件路由对象数组
// 返回项目中所有路由对象 - 不涉及权限问题
function getAllRoutes() {
  const routeFiles = require.context('../router/main', true, /\.ts/)
  if (!routeFiles || routeFiles.length <= 0) {
    msg.info('项目目录：src/router/main 下没有路由文件！')
    return
  }

  const allRoutes: RouteRecordRaw[] = []
  routeFiles.keys().forEach((item) => {
    const route = require('../router/main' + item.split('.')[1])
    allRoutes.push(route.default)
  })

  return allRoutes
}

// 根据用户菜单权限返回对应的路由数组
// 有哪些权限返回哪些路由数组 - 动态路由
function getUserRoutes(menus: any[]) {
  const allRoutes = getAllRoutes()

  if (!allRoutes || allRoutes.length <= 0) {
    msg.info('没有构建项目全部路由，无法映射用户路由数组！')
    return
  }

  const userRoutes: RouteRecordRaw[] = []
  const _recurseMenus = (subMenus: any[]) => {
    if (Array.isArray(subMenus)) {
      subMenus.forEach((item) => {
        if (item.type !== 2) {
          _recurseMenus(item.children)
        } else {
          const currentRoute = allRoutes.find(
            (oneRoute) => oneRoute.path === item.url
          )
          if (currentRoute) userRoutes.push(currentRoute)
          if (!firstRoute) firstRoute = currentRoute
        }
      })
    }
  }

  _recurseMenus(menus)

  return userRoutes
}

/**
 * 得到页面当前路径对应的菜单权限对象并返回
 * @param userMenus 当前登录系统的用户拥有的菜单项权限 - 树形结构
 * @param path 浏览器当前 url - 通过 useRoute().path 获得的路径
 * @returns 返回菜单对象
 */
function getMenu8Path(userMenus: any[], path: string): any {
  const retMenu: any[] = []
  const _recurseUserMenus = (userMenus: any[]) => {
    userMenus.forEach((item) => {
      if (item.url === path) {
        retMenu.push(item)
      } else {
        if (item.children) _recurseUserMenus(item.children)
      }
    })
  }

  _recurseUserMenus(userMenus)

  return retMenu.length > 0 ? retMenu[0] : null
}

export { getAllRoutes, getUserRoutes, getMenu8Path }
